package server

import (
	"Bulb/data"
	"Bulb/packet"
	"fmt"
	"html/template"
	"log"
	"net/http"

	"github.com/gorilla/websocket"
)

func InitAdmin() {
	http.HandleFunc("/admin", handleAdmin)
	http.HandleFunc("/admin/ws", handleAdminWS)
}

func handleAdmin(w http.ResponseWriter, r *http.Request) {
	temp := template.Must(template.ParseFiles("www/admin.html"))
	temp.Execute(w, nil)
}
func handleAdminWS(w http.ResponseWriter, r *http.Request) {
	conn, err := websocket.Upgrade(w, r, nil, 0, 0)
	if err != nil {
		log.Println("升级失败:", err)
		return
	}
	defer conn.Close()
	hub.mutex.Lock()
	hub.clients[0] = conn
	hub.mutex.Unlock()
	fmt.Println("New Conn ", 0)
	SendToAdmin(packet.EncodeServerPacket(packet.NewChatMessageInitPacket(data.GetLatestMessages())))
	SendToAdmin(packet.EncodeServerPacket(packet.NewUserDataInitPacket(data.GetAllUserData())))
	for {
		_, message, err := conn.ReadMessage()
		if err != nil {
			log.Println("读消息失败:", err)
			hub.unregister <- 0
			break
		}
		pack := packet.ParseClientPacket(string(message))
		handleAdminClientPacket(pack)
		//fmt.Println(message)
	}
}
func handleAdminClientPacket(pack packet.ClientPacket) {
	switch pack.Action {
	case "turn_off_all_lights":
		data.TurnOffAllLights()
		BroadcastMessage(packet.EncodeServerPacket(packet.NewBulbSetPacket("off")))
		SendToAdmin(packet.EncodeServerPacket(packet.NewUserDataInitPacket(data.GetAllUserData())))
	case "send_admin_message":
		data.AddMessage(0, pack.Data)
		hub.broadcast <- packet.EncodeServerPacket(
			packet.NewChatMessagePacket(
				data.Message{Sender: 0, Content: pack.Data},
			),
		)
	}
}
